package com.SmartClassroom.system.controller;

import com.SmartClassroom.system.annotation.AuthCheck;
import com.SmartClassroom.system.common.*;
import com.SmartClassroom.system.constant.UserConstant;
import com.SmartClassroom.system.exception.BusinessException;
import com.SmartClassroom.system.exception.ThrowUtils;
import com.SmartClassroom.system.model.domain.Attendance;
import com.SmartClassroom.system.model.domain.Course;
import com.SmartClassroom.system.model.domain.User;
import com.SmartClassroom.system.model.dto.attendance.AttendanceAddRequest;
import com.SmartClassroom.system.model.dto.attendance.AttendanceQueryRequest;
import com.SmartClassroom.system.model.dto.attendance.AttendanceUpdateRequest;
import com.SmartClassroom.system.model.vo.AttendanceVO;
import com.SmartClassroom.system.model.vo.LoginUserVO;
import com.SmartClassroom.system.service.AttendanceService;
import com.SmartClassroom.system.service.CourseService;
import com.SmartClassroom.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

import static com.SmartClassroom.system.common.CourseUtil.setAttendanceId;

/**
 * 签到接口
 *
 * @author baijiayu
 */
@RestController
@RequestMapping("/attendance")
@Slf4j
@Api(tags = { "签到接口" })
public class AttendanceController {

    @Resource
    private UserService userService;

    @Resource
    private AttendanceService attendanceService;

    // region 登录相关

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    // endregion

    // region 增删改查

    /**
     * 签到签退接口
     *
     * @param attendanceAddRequest 签到签退请求参数
     * @param request              HTTP请求对象
     * @return 包含签到签退记录ID的响应
     */
    @PostMapping("/add")
    @ApiOperation(value = "签到签退")
    public BaseResponse<Integer> addAttendance(@RequestBody AttendanceAddRequest attendanceAddRequest,
            HttpServletRequest request) {
        // 检查请求参数是否为空
        if (attendanceAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        // 创建签到签退记录对象
        Attendance attendance = new Attendance();

        // 获取当前登录用户信息
        BaseResponse<LoginUserVO> loginUserResponse = getLoginUser(request);
        LoginUserVO loginUser = loginUserResponse.getData();

        switch (attendanceAddRequest.getCourseName()) {
            case "高数":
                attendance.setCourseId(1);
                break;
            case "大学英语":
                attendance.setCourseId(2);
                break;
            case "线性代数":
                attendance.setCourseId(3);
                break;
            case "离散数学":
                attendance.setCourseId(4);
                break;
            case "Java编程":
                attendance.setCourseId(5);
                break;
            case "网络安全":
                attendance.setCourseId(6);
                break;
            case "SDN网络编程编程":
                attendance.setCourseId(7);
                break;
            case "物理":
                attendance.setCourseId(8);
                break;
            default:
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "无效的课程: 请联系管理员");
        }

        attendance.setStudentId(loginUser.getId()); // 设置学生ID
        String systemStatus = convertUserStatusToSystemStatus(attendanceAddRequest.getStatus());
        attendance.setStatus(systemStatus);
        attendance.setTimestamp(new Date()); // 设置签到时间戳

        // 保存签到签退记录
        boolean saveResult = attendanceService.save(attendance);
        // 如果保存失败，抛出业务异常
        ThrowUtils.throwIf(!saveResult, ErrorCode.OPERATION_ERROR);

        // 返回签到签退记录ID
        return ResultUtils.success(attendance.getAttendanceId());
    }

    /**
     * 删除签到记录
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除签到记录（仅管理员）")
    public BaseResponse<Boolean> deleteAttendance(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        boolean result = attendanceService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");
        return ResultUtils.success(result);
    }

    /**
     * 更新签到签退记录（仅管理员）
     *
     * @param attendanceUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "更新签到签退记录（仅管理员）")
    public BaseResponse<Boolean> updateAttendance(@RequestBody AttendanceUpdateRequest attendanceUpdateRequest) {
        if (attendanceUpdateRequest == null || attendanceUpdateRequest.getAttendanceId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 从请求中提取数据并填充到 Attendance 对象中
        Attendance attendance = new Attendance();
        attendance.setAttendanceId(attendanceUpdateRequest.getAttendanceId());

        // 使用 CourseUtil 设置 CourseId
        switch (attendanceUpdateRequest.getCourseName()) {
            case "高数":
                attendance.setCourseId(1);
                break;
            case "大学英语":
                attendance.setCourseId(2);
                break;
            case "线性代数":
                attendance.setCourseId(3);
                break;
            case "离散数学":
                attendance.setCourseId(4);
                break;
            case "Java编程":
                attendance.setCourseId(5);
                break;
            case "网络安全":
                attendance.setCourseId(6);
                break;
            case "SDN网络编程编程":
                attendance.setCourseId(7);
                break;
            case "物理":
                attendance.setCourseId(8);
                break;
            default:
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "无效的课程: 请联系管理员");
        }

        // 将用户输入的签到签退状态转换为系统内部的状态
        String userStatus = attendanceUpdateRequest.getStatus();
        String systemStatus = convertUserStatusToSystemStatus(userStatus);
        attendance.setStatus(systemStatus);

        // 根据实际情况添加其他字段

        boolean result = attendanceService.updateById(attendance);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新失败");
        return ResultUtils.success(true);
    }

    /**
     * 将用户输入的签到签退状态转换为系统内部的状态
     *
     * @param userStatus 用户输入的状态（例如 "签到" 或 "签退"）
     * @return 系统内部的状态（例如 "in" 或 "out"）
     */
    private String convertUserStatusToSystemStatus(String userStatus) {
        if ("签到".equals(userStatus)) {
            return "in";
        } else if ("签退".equals(userStatus)) {
            return "out";
        } else {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无效的签到签退状态");
        }
    }

    /**
     * 查询全部的签到记录
     *
     * @param attendanceQueryRequest
     * @return
     */
    @PostMapping("/get/all")
    @ApiOperation(value = "查询全部的签到记录")
    public BaseResponse<Page<AttendanceVO>> listAttendance(@RequestBody AttendanceQueryRequest attendanceQueryRequest) {
        // 分页参数
        long current = attendanceQueryRequest.getCurrent() == 0 ? 1 : attendanceQueryRequest.getCurrent();
        long size = attendanceQueryRequest.getPageSize() == 0 ? 10 : attendanceQueryRequest.getPageSize();

        // 分页对象
        Page<AttendanceVO> pageParam = new Page<>(current, size);
        Page<AttendanceVO> attendanceVOPage = attendanceService.getQueryWrapper(pageParam, attendanceQueryRequest);

        return ResultUtils.success(attendanceVOPage);
    }

    /**
     * 根据 学生id 获取包装类
     *
     * @param request
     * @return
     */
    @PostMapping("/get/all/my")
    @ApiOperation(value = "根据 学生id 获取包装类")
    public BaseResponse<Page<AttendanceVO>> getAttendanceVOId(
            @RequestBody AttendanceQueryRequest attendanceQueryRequest, HttpServletRequest request) {
        BaseResponse<LoginUserVO> loginUser = getLoginUser(request);
        Long userId = loginUser.getData().getId();

        // 分页参数
        long current = attendanceQueryRequest.getCurrent() == 0 ? 1 : attendanceQueryRequest.getCurrent();
        long size = attendanceQueryRequest.getPageSize() == 0 ? 10 : attendanceQueryRequest.getPageSize();

        // 分页对象
        Page<AttendanceVO> pageParam = new Page<>(current, size);
        Page<AttendanceVO> attendanceVOPage = attendanceService.getQueryById(pageParam, attendanceQueryRequest, userId);

        return ResultUtils.success(attendanceVOPage);
    }
}
